/**
 * 获取树状数据的所有子节点
 * @param {*} tree 树状数据
 * @param {*} key 唯一key
 */
export const getChild = (tree, key) => {
    let result  = []
    const traverse = (arr, key) => {
        for (let item of arr) {
            if (item[key] && item[key].length) {
                traverse(item[key], key)
            } else {
                result.push(item)
            }
        }
    }
    traverse(tree, key)
    return result;
}

/**
 * 根据当前key的值获取目标key的值
 * @param {*} tree 树状数据
 * @param {*} currentKey 唯一key
 * @param {*} targetKey 名称key
 * @param {*} key 当前key的值
 * @param {*} childrenKey 子节点的children的key,默认为children
 */
export const getTargetKey = (tree, currentKey, targetKey, value,childrenKey='children') => {
    let name=''
    const traverse=(arr)=>{
        for (let item of arr) {
            if (item[currentKey] == value) {
                name=item[targetKey]
            } else if (item[childrenKey] && item[childrenKey].length) {
                traverse(item[childrenKey], currentKey, targetKey, value)
            }
        }
    }
    traverse(tree);
    return name;
}

/**
 * 根据子节点key获取所在所有父节点数组（扁平）
 * @param {*} tree 树状数据
 * @param {*} key 唯一key
 * @param {*} value 唯一key的值
 * @param {*} childrenKey 子节点的children的key,默认为children
 */
export const getParentList=(tree,key,value,childrenKey='children')=>{
    let result = [];
    const traverse = (arr) => {
        for (let item of arr) {
            if (item[key] == value) {
                result.unshift(item);
                return true;
            } else if (item[childrenKey] && item[childrenKey].length) {
                if (traverse(item[childrenKey])) {
                    result.unshift(item);
                    return true;
                };
            }
        }
    }
    traverse(tree);
    return result;
}

/**
 * 过滤掉空的子数组
 * @param {*} tree 树状数据
 * @param {*} childrenKey 子节点的children的key
 */
export const filterEmpty = (tree,childrenKey='children') => {
    // 遍历
    const traverse = (arr) => {
        for (let item of arr) {
            if (item[childrenKey] && item[childrenKey].length == 0) {
                delete item[childrenKey];
            } else if (item[childrenKey] && item[childrenKey].length > 0) {
                traverse(item[childrenKey]);
            }
        }
    }
    traverse(tree)
    return tree;
}
